import React, { Component } from "react";
import Nav from "../nav/Nav";
import { getSearchGoodsList, addCart, getCart } from "../../data/api";
import { Carousel, WingBlank, Toast,Badge } from "antd-mobile";
import "./GoodDatail.scss";
import { connect } from "react-redux"
class ListSearch extends Component {
  state = {
    goods_list: {},
    data: [],
    imgHeight: 180,
    is_promote: false,
    prcNum: 1,
    num: 1,
    passTime: 0,
    nowTime: 0,
    h: 0,
    m: 0,
    s: 0,
    message: {}
  };
  async componentDidMount() {
    let { goods_id } = this.props.match.params;
    let prcNum = Math.floor((Math.random() * 100) + 100)
    let num = Math.floor((Math.random() * 30) + 50)
    setInterval(() => {
      let passTime = new Date('2020,11,27,22:00:00')
      let nowTime = new Date()
      let timex = parseInt((passTime - nowTime) / 1000)
      let h = parseInt(timex / 3600)
      if (h < 10) {
        h = '0' + h
      }
      let m = parseInt((timex - h * 3600) / 60)
      if (m < 10) {
        m = '0' + m
      }
      let s = timex - h * 3600 - m * 60
      if (s < 10) {
        s = '0' + s
      }
      this.setState({
        passTime,
        nowTime,
        h,
        m,
        s
      })
    }, 1000)


    let res = await getSearchGoodsList({
      goods_id: goods_id,
    });
    this.setState({
      goods_list: res.message,
      data: res.message.pics,
      prcNum,
      num,
      message: res.message
    });
    // console.log(res)
    if (res.message.is_promote) {
      this.setState({
        is_promote: true,
      });
    }

  }
  //加入购物车  点击购物车跳转到购物车页面
  handleAddCar = async (params) => {
    let token = sessionStorage.getItem("token");
    // console.log(token);
    if (token) {
      let info = {};
      info.cat_id = this.state.message.cat_id;
      info.goods_id = this.state.message.goods_id;
      info.goods_name = this.state.message.goods_name;
      info.goods_number = this.state.message.goods_number;
      info.goods_price = this.state.message.goods_price;
      info.goods_small_logo = this.state.message.goods_small_logo;
      info.goods_weight = this.state.message.goods_weight;
      //发送添加购物车的请求
      let res = await addCart({ info: JSON.stringify(info) });
      // console.log(res);
      if (res.meta.status === 200) {
        Toast.info("加入购物车成功", 1);
      }
    } else {
      Toast.info("你还没有登录，请先登录")
    }
  }
  //立即购买   跳转到立即购买页面
  handleGoCar = () => {
    this.props.buyNow(1,this.state.goods_list.goods_price);
    // console.log(this.state.goods_list.goods_price);
    this.props.history.push("/pay/"+this.state.goods_list.goods_id);
  }
  //跳转到购物车
  goToCart = () => {
    this.props.history.push("/cart");
  }

  render() {
    // console.log(this.state.goods_list);
    // console.log(this.state.attr)

    return (
      <div>
        <Nav title="商品详情" left={true}></Nav>
        <WingBlank>
          <Carousel autoplay={true} infinite={true}>
            {this.state.data.map((val) => (
              <a
                key={val}
                href={val.pics_mid_url}
                style={{
                  display: "inline-block",
                  width: "100%",
                  height: this.state.imgHeight,
                }}
              >
                <img
                  src={val.pics_mid}
                  alt=""
                  style={{ width: "100%", verticalAlign: "top" }}
                  onLoad={() => {
                    // fire window resize event to change height
                    window.dispatchEvent(new Event("resize"));
                    this.setState({ imgHeight: "auto" });
                  }}
                />
              </a>
            ))}
          </Carousel>
        </WingBlank>
        <div className="goodsListPrice">
          <div className="goodsListPriceLeft">
            <div className="goodsLeftNum">
              ￥{this.state.goods_list.goods_price}
            </div>
            <div className="goodsLeftNummin">
              <s className="goodsLeftJJ">
                ￥{this.state.goods_list.goods_price + this.state.prcNum}
              </s>
              <p className="goodsLeftNums">
                {this.state.num}件已售
              </p>
            </div>
          </div>
          <div className="goodsListPriceRight">
            <div className="goodsRightTimeText">距离活动结束余</div>
            <div className="goodsRightTimeNum">
              <span className="timeList">{this.state.h}</span>
              <span className="timeListD">:</span>
              <span className="timeList">{this.state.m}</span>
              <span className="timeListD">:</span>
              <span className="timeList">{this.state.s}</span>
            </div>
          </div>
        </div>

        <div className="goodsShopFree">
          享6期免息。可免80元。每期120元（每日22.2元）
        </div>
        <div className="goodsShopName">{this.state.goods_list.goods_name}</div>
        <div className="goodsShopExpress">
          <div className="goodsExpress">
            快递：{this.state.is_promote ? "需要运费" : "免运费"}
          </div>
          <div className="goodsMothNum">月销量：1000+件</div>
        </div>
        <div className="goodsShopPromotion">
          <div className="goodsPromotionLeft">促销:</div>
          <div className="goodsPromotionRight">
            <span className="PromotionLeft">促销</span>
            <span className="PromotionRight">满400减100元</span>
          </div>
        </div>
        <div className="goodsShopService">
          <div className="serviceLeft">服务</div>
          <div className="serviceRight">
            假一赔十 | 送货入户 | 极速退款 | 七天无理由退换
          </div>
        </div>
        <div className="goodsShopChoice">
          <div className="choiceLeft">选择</div>
          <div className="choiceRight">
            <span className="choiceInt">配送至：</span>
            <span className="choiceIntDiTu">罗湖区</span>
            <span className="choiceInt">请选择颜色分类</span>
          </div>
        </div>
        <div className="goodsShopImgList">
          {this.state.data.map((v, i) => {
            return (
              <img className="shopsImgList" key={i} src={
                v.pics_mid
              }></img>
            )
          })}
        </div>

        <div className="goodsShopCart">
          <div className="shopCart" onClick={this.goToCart}>
            <i className="shopsCartIcon iconfont icon-gouwuche"></i>
            <Badge
              text={this.props.totalNum}
              overflowCount={50}
              style={{
                position: 'absolute',
                width: 'auto',
                height: 'auto',
                top: '-20px',
                right: '-18px',
                fontSize: 8,
                borderRadius: '50%',
                backgroundColor: '#e4393c',
                textAlign: 'center',
                color: 'white'
              }}>
            </Badge>
          </div>
          <div className="shopsGoBackCart" onClick={this.handleAddCar}>加入购物车</div>
          <div className="shopsNow" onClick={this.handleGoCar}>立即购买</div>
        </div>
      </div>
    );
  }
}
const mapStateToProps = (state) => {
  return {
    totalNum: state.cartReducer.totalNum
  }
}
const mapDispatchToProps = (dispatch)=>{
  return {
      buyNow:(totalNum,totalPrice)=>{
          dispatch({
              type:"BUY_NOW",
              payload:{
                  totalNum,
                  totalPrice
              }
          })
      }
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(ListSearch)